/**
 * @author yxw
 * date : 2013年10月5日 下午2:15:57 
 */
package com.tzinfo.tzt.activity;


import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.config.FileConfig;
import com.tzinfo.tzt.domain.SeeNote;
import com.tzinfo.tzt.service.HouseSeeNoteService;
import com.tzinfo.tzt.util.FileTools;
import com.tzinfo.tzt.util.StringTools;

public class SeeNotesDetailActivity extends BaseActivity implements OnClickListener {

	private SeeNote seeNote = null;

	// UI组件
	private Button backBtn, editBtn, addImageBtn;
	private TextView[] textView = new TextView[11];
	private RelativeLayout[] layoutShow = new RelativeLayout[3];
	private RelativeLayout[] layoutAdd = new RelativeLayout[3];
	private LinearLayout imagesLayout = null;
	private HouseSeeNoteService seeNoteService=null;

	protected AlertDialog dlg;
	protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");// 设置日期格式
	protected SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_see_notes);
		Intent thisIntent = this.getIntent();
		seeNote = (SeeNote) thisIntent.getSerializableExtra("seeNote");
		seeNoteService=new HouseSeeNoteService(this);
		init();
	}

	private void init() {

		// 图片插入
		imagesLayout = (LinearLayout) this
				.findViewById(R.id.layout_images_insert);

		addImageBtn = (Button) this.findViewById(R.id.bt_add_image);
		addImageBtn.setOnClickListener(this);
		backBtn = (Button) this.findViewById(R.id.bt_back);
		backBtn.setOnClickListener(this);
		editBtn = (Button) this.findViewById(R.id.bt_edit);
		editBtn.setOnClickListener(this);
		layoutShow[0] = (RelativeLayout) this.findViewById(R.id.layout_group);
		layoutShow[1] = (RelativeLayout) this
				.findViewById(R.id.layout_show_agent);
		layoutShow[1].setOnClickListener(this);
		layoutShow[2] = (RelativeLayout) this
				.findViewById(R.id.layout_add_time_show);

		layoutAdd[0] = (RelativeLayout) this.findViewById(R.id.layout_add_bar);
		layoutAdd[1] = (RelativeLayout) this
				.findViewById(R.id.layout_add_agent);
		layoutAdd[2] = (RelativeLayout) this.findViewById(R.id.layout_add_time);
		for (int i = 0; i < layoutAdd.length; i++) {
			layoutAdd[i].setOnClickListener(this);
		}

		textView[0] = (TextView) this.findViewById(R.id.text_apartment_name);
		textView[1] = (TextView) this.findViewById(R.id.text_apartment_address);
		textView[2] = (TextView) this.findViewById(R.id.text_price);
		textView[3] = (TextView) this.findViewById(R.id.text_floor);
		textView[4] = (TextView) this.findViewById(R.id.text_type);
		textView[5] = (TextView) this.findViewById(R.id.text_size);
		textView[6] = (TextView) this.findViewById(R.id.text_direction);
		textView[7] = (TextView) this.findViewById(R.id.text_remark);
		textView[8] = (TextView) this.findViewById(R.id.text_agent_name);
		textView[9] = (TextView) this.findViewById(R.id.text_agent_tel);
		textView[10] = (TextView) this.findViewById(R.id.text_notes_time_show);

		textView[0].setText(seeNote.getVillageName());
		textView[1].setText(seeNote.getVillageAddress());
		// 判断基本信息是否为空
		if (StringTools.isEmpty(seeNote.getPrice())
				&& StringTools.isEmpty(seeNote.getFloor())
				&& StringTools.isEmpty(seeNote.getType())
				&& "0".equals(seeNote.getSize() + "")
				&& StringTools.isEmpty(seeNote.getDirection())
				&& StringTools.isEmpty(seeNote.getRemark())) {
			layoutShow[0].setVisibility(View.GONE);
			layoutAdd[0].setVisibility(View.VISIBLE);

		} else {
			if (!StringTools.isEmpty(seeNote.getPrice())) {
				textView[2].setText(seeNote.getPrice() + "万");
			}
			textView[3].setText(seeNote.getFloor());
			textView[4].setText(seeNote.getType());
			if (!"0".equals(seeNote.getSize() + "")) {
				textView[5].setText(seeNote.getSize() + "平米");
			}
			textView[6].setText(seeNote.getDirection());
			textView[7].setText(seeNote.getRemark());
			layoutShow[0].setVisibility(View.VISIBLE);
			layoutAdd[0].setVisibility(View.GONE);
		}
		if (StringTools.isEmpty(seeNote.getAgentName())
				&& StringTools.isEmpty(seeNote.getAgentTel())) {
			layoutShow[1].setVisibility(View.GONE);
			layoutAdd[1].setVisibility(View.VISIBLE);
		} else {
			textView[8].setText(seeNote.getAgentName());
			textView[9].setText(seeNote.getAgentTel());
			layoutShow[1].setVisibility(View.VISIBLE);
			layoutAdd[1].setVisibility(View.GONE);
		}
		if (StringTools.isEmpty(seeNote.getDate())
				&& StringTools.isEmpty(seeNote.getTime())) {
			layoutShow[2].setVisibility(View.GONE);
			layoutAdd[2].setVisibility(View.VISIBLE);
		} else {
			textView[10].setText((seeNote.getDate() + " " + seeNote.getTime())
					.trim());
			layoutShow[2].setVisibility(View.VISIBLE);
			layoutAdd[2].setVisibility(View.GONE);
		}
		
		new Thread(imageLoadRun).start();
		
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent(SeeNotesDetailActivity.this,
				SeeNotesUpdateActivity.class);
		switch (v.getId()) {
		case R.id.layout_show_agent:
			String tel = seeNote.getAgentTel();
			if (StringTools.isEmpty(tel)) {
				Toast.makeText(SeeNotesDetailActivity.this, "抱歉，您没有添加该经纪人的电话！！", 5000)
						.show();
			} else {
				Intent phoneIntent = new Intent("android.intent.action.CALL",
						Uri.parse("tel:" + tel));
				startActivity(phoneIntent);
			}
			break;
		case R.id.bt_back:
			this.finish();
			break;
		case R.id.bt_edit:
			intent.putExtra("seeNote", seeNote);
			startActivityForResult(intent, 1);
			break;
		case R.id.layout_add_bar:
			intent.putExtra("seeNote", seeNote);
			startActivityForResult(intent, 1);
			break;
		case R.id.layout_add_agent:
			intent.putExtra("seeNote", seeNote);
			startActivityForResult(intent, 1);
			break;
		case R.id.layout_add_time:
			intent.putExtra("seeNote", seeNote);
			startActivityForResult(intent, 1);
			break;
		case R.id.bt_add_image:
			showAddImageDialog();
			break;
		default:
			break;
		}

	}

	// 显示选择相册or照片
	private void showAddImageDialog() {
		final CharSequence[] items = { "相册", "拍照", "取消" };

		dlg = new AlertDialog.Builder(this).setTitle("选择照片")
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// 这里item是根据选择的方式， 在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
						if (which == 0) {
							Intent getImage = new Intent(
									Intent.ACTION_GET_CONTENT);
							getImage.addCategory(Intent.CATEGORY_OPENABLE);
							getImage.setType("image/jpeg");
							startActivityForResult(getImage, 2);
						} else if (which == 1) {
							Intent getImageByCamera = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							File tempFile= new File(FileConfig.TEMP_PATH);
							if(!tempFile.isDirectory()){
								tempFile.mkdirs();
							}
							Uri imageUri = Uri.fromFile(new File(FileConfig.TEMP_PATH,FileConfig.TEMP_FILE));  
							//指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换  
							getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);  
							startActivityForResult(getImageByCamera, 3);
						} else {
							dlg.dismiss();
						}

					}
				}).create();
		dlg.show();
	}

	private void addImagelayout(Bitmap bm,String path) {
		LayoutParams lp1 = new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		LinearLayout images = (LinearLayout) getLayoutInflater().inflate(
				R.layout.layout_seenote_image, null);
		ImageView imageView = (ImageView) images.findViewById(R.id.imageView);
		imageView.setImageBitmap(bm);
		TextView timeText= (TextView) images.findViewById(R.id.text_time);
		String[] times=path.split("_");
		if(times.length>1){
			String[] timess=times[times.length-1].split(" ");
			timeText.setText(timess[0]+" "+timess[1].replaceAll("-", ":"));
		}else{
			timeText.setText(df.format(new Date()));
		}
		images.setOnClickListener(new MyOnClickListener(path));
		imagesLayout.addView(images, lp1);
	}

	class MyOnClickListener implements OnClickListener {
		private String path;
		public MyOnClickListener(String path){
			this.path=path;
		}
		@Override
		public void onClick(View v) {
			Intent intent=new Intent(SeeNotesDetailActivity.this, SeeNoteViewIamge.class);
			intent.putExtra("path", path);
			startActivity(intent);
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Bitmap myBitmap;
		switch (requestCode) {
		case 1:
			if (resultCode == 1) {
				SeeNote temp = (SeeNote) data.getSerializableExtra("seeNote");
				if (!temp.toString().equals(seeNote.toString())) {
					seeNote = temp;
					imagesLayout.removeAllViews();
					init();
				}
			}
			if (resultCode == 2) {
				this.finish();
			}
			break;
		case 2:
			try {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
//				Log.e("picturePath", picturePath);
				cursor.close();
				// 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
				BitmapFactory.Options option = new BitmapFactory.Options();
				Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
				option.inSampleSize = FileTools.getInSampleSize(bitmap);
				FileInputStream fin = new FileInputStream(picturePath);
				String path=FileTools.saveInputStreamInSD(fin, "seenote_"+sdf.format(new Date()));
//				String path=FileTools.saveBitmapInSD("seenote_"+sdf.format(new Date()), bitmap);
				bitmap.recycle();
//				Toast.makeText(this, "path=" + path, 5000).show();
				addImagelayout(BitmapFactory.decodeFile(path, option),path);
				//保存到本地数据库
				List<String> list=seeNote.getImages();
				list.add(path);
				seeNote.setImages(list);
				seeNoteService.saveSeeNoteImages(seeNote);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			break;
		case 3:
			try {
//				Bundle extras = data.getExtras();
//				myBitmap = (Bitmap) extras.get("data");
//				BitmapFactory.Options option = new BitmapFactory.Options();
//				option.inSampleSize = FileTools.getInSampleSize(myBitmap);
//				String path=FileTools.saveBitmapInSD("seenote_"+sdf.format(new Date()), myBitmap);
//				myBitmap.recycle();
////				Toast.makeText(this, "path=" + path, 5000).show();
//				addImagelayout(BitmapFactory.decodeFile(path,option),path);
//				//保存到本地数据库
//				List<String> list=seeNote.getImages();
//				list.add(path);
//				seeNote.setImages(list);
//				seeNoteService.saveSeeNoteImages(seeNote);
				
				// 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
				BitmapFactory.Options option = new BitmapFactory.Options();
				Bitmap bitmap = BitmapFactory.decodeFile(FileConfig.TEMP_PATH+"/"+FileConfig.TEMP_FILE);
				option.inSampleSize = FileTools.getInSampleSize(bitmap);
				FileInputStream fin = new FileInputStream(FileConfig.TEMP_PATH+"/"+FileConfig.TEMP_FILE);
				String path=FileTools.saveInputStreamInSD(fin, "seenote_"+sdf.format(new Date()));
//				String path=FileTools.saveBitmapInSD("seenote_"+sdf.format(new Date()), bitmap);
				bitmap.recycle();
//				Toast.makeText(this, "path=" + path, 5000).show();
				addImagelayout(BitmapFactory.decodeFile(path, option),path);
				//保存到本地数据库
				List<String> list=seeNote.getImages();
				list.add(path);
				seeNote.setImages(list);
				seeNoteService.saveSeeNoteImages(seeNote);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}

			break;
		default:
			break;
		}
	}
	

	//用线程加载图片 防止点击后卡机
	Runnable imageLoadRun =new Runnable() {
		@Override
		public void run() {
			List<String> images=seeNote.getImages();
			for (int i = 0; images!=null&&i < images.size(); i++) {
				Message msg = handler.obtainMessage();
				Bitmap bitmap = BitmapFactory.decodeFile(images.get(i));
				if(bitmap!=null){
					BitmapFactory.Options option = new BitmapFactory.Options();
					option.inSampleSize = FileTools.getInSampleSize(bitmap);
					bitmap =BitmapFactory.decodeFile(images.get(i), option);
					msg.arg1 = 1;
					Map<String, Object> map=new HashMap<String, Object>();
					map.put("bitmap", bitmap);
					map.put("path", images.get(i));
					msg.obj = map;
				}else{
					msg.obj = images.get(i);
					msg.arg1 = -1;
				}
				handler.sendMessage(msg);
			}
			seeNoteService.saveSeeNote(seeNote);
		}
	};
	
	
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case -1:
				seeNote.deleteImageByPath((String) msg.obj);
				break;
			case 1:
				Map<String, Object> map=(Map<String, Object>) msg.obj;
				addImagelayout((Bitmap)map.get("bitmap"),(String)map.get("path"));
				break;
			}
		}
	};

}
